<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">


  <meta name="msapplication-config" content="/images/browserconfig.xml">



  <meta name="keywords" content="Nginx,">





  <link rel="alternate" href="/atom.xml" title="两万" type="application/atom+xml">






<meta name="description" content="简述 Nginx nginx有一个主进程和几个工作进程。(参看 worker_processes).  主进程的主要目的是为了读取和评估配置并且维护工作进程。工作进程处理实际请求。 nginx在工作进程中采用事件驱动模型和OS依赖机制有效分配请求。 工作进程的数量取决于配置文件中定义的固定值或者是通过有效的CPU核数自动判定数量。 工作进程的数量在配置文件中定义，可据给定的配置对工作进程的数量进行">
<meta name="keywords" content="Nginx">
<meta property="og:type" content="article">
<meta property="og:title" content="Nginx入门指南">
<meta property="og:url" content="http://blog.bevexed.top/2019/09/06/nginx入门指南/index.html">
<meta property="og:site_name" content="两万">
<meta property="og:description" content="简述 Nginx nginx有一个主进程和几个工作进程。(参看 worker_processes).  主进程的主要目的是为了读取和评估配置并且维护工作进程。工作进程处理实际请求。 nginx在工作进程中采用事件驱动模型和OS依赖机制有效分配请求。 工作进程的数量取决于配置文件中定义的固定值或者是通过有效的CPU核数自动判定数量。 工作进程的数量在配置文件中定义，可据给定的配置对工作进程的数量进行">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-10T06:09:19.085Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Nginx入门指南">
<meta name="twitter:description" content="简述 Nginx nginx有一个主进程和几个工作进程。(参看 worker_processes).  主进程的主要目的是为了读取和评估配置并且维护工作进程。工作进程处理实际请求。 nginx在工作进程中采用事件驱动模型和OS依赖机制有效分配请求。 工作进程的数量取决于配置文件中定义的固定值或者是通过有效的CPU核数自动判定数量。 工作进程的数量在配置文件中定义，可据给定的配置对工作进程的数量进行">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.bevexed.top/2019/09/06/nginx入门指南/">





  <title>Nginx入门指南 | 两万</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?4fdb363593835184af3e5b1a4874f9db";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">两万</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Daily</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.bevexed.top/2019/09/06/nginx入门指南/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="两万">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/IMG_2021.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="两万">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Nginx入门指南</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-06T13:52:09+08:00">
                2019-09-06
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/服务器/" itemprop="url" rel="index">
                    <span itemprop="name">服务器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/09/06/nginx入门指南/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/09/06/nginx入门指南/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2019/09/06/nginx入门指南/" class="leancloud_visitors" data-flag-title="Nginx入门指南">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="简述-Nginx"><a href="#简述-Nginx" class="headerlink" title="简述 Nginx"></a>简述 Nginx</h2><ul>
<li><p>nginx有一个主进程和几个工作进程。(参看 worker_processes).</p>
<ul>
<li>主进程的主要目的是为了读取和评估配置并且维护工作进程。工作进程处理实际请求。</li>
<li>nginx在工作进程中采用事件驱动模型和OS依赖机制有效分配请求。</li>
<li>工作进程的数量取决于配置文件中定义的固定值或者是通过有效的CPU核数自动判定数量。</li>
<li>工作进程的数量在配置文件中定义，可据给定的配置对工作进程的数量进行固定，也可以根据可用CPU内核的数量进行自动调整。</li>
</ul>
</li>
<li><p>nginx及其各模块的工作方式取决于配置文件。</p>
<ul>
<li>默认情况下，配置文件名为nginx.conf，并放置在/usr/local/nginx/conf、/etc/nginx或/usr/local/etc/nginx.目录中。</li>
</ul>
</li>
</ul>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><blockquote>
<p>自行参考 Installing nginx 页面<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; brew install ngnix</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h2 id="启动-停止-和重新加载配置文件"><a href="#启动-停止-和重新加载配置文件" class="headerlink" title="启动, 停止, 和重新加载配置文件"></a>启动, 停止, 和重新加载配置文件</h2><blockquote>
<p>启动的时候直接运行nginx.exe或者nginx。如果nginx已经启动，就可以直接使用参数-s 来进行调用执行，具体的使用语法如下：</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; nginx -s signal</span><br></pre></td></tr></table></figure>
<p>signal 的位置可以是如下参数：</p>
<ul>
<li>stop — 指令一经发出，直接停止</li>
<li>quit — 等待所有的请求完成，再停止</li>
<li>reload — 重新加载配置文件nginx.conf</li>
<li>reopen — 重新打开日志文件</li>
</ul>
<h2 id="配置文件结构"><a href="#配置文件结构" class="headerlink" title="配置文件结构"></a>配置文件结构</h2><ul>
<li>nginx由模块组成<ul>
<li>这些模块由配置文件中指定的指令控制。</li>
<li>指令分为简单指令和块指令。</li>
<li>一个简单的指令由名称和参数组成，这些名称和参数由空格分隔，并以分号(;)结尾。</li>
<li>块指令具有与简单指令相同的结构，但它的结尾不是分号，而是一组由大括号({、})包围的附加指令。</li>
<li>如果一个块指令在大括号中包含其他指令，则这个块指令又叫做上下文 (例如: events, http, server, 和location).</li>
<li>放在任何上下文之外的配置文件中的指令被认为是在主上下文中。</li>
<li>event 和 http 指令驻留在主上下文中，server 驻留在 http 中，location 驻留在 server中。</li>
<li>一行中在#符号后面的是注释</li>
</ul>
</li>
</ul>
<h3 id="全局块"><a href="#全局块" class="headerlink" title="全局块"></a>全局块</h3><ul>
<li>从配置文件开始到 events 块之间的内容</li>
<li>主要设置影响 Ngnix 服务器整体运行的配置指令</li>
</ul>
<h3 id="event-块"><a href="#event-块" class="headerlink" title="event 块"></a>event 块</h3><ul>
<li>涉及的指令主要影响 Nginx 服务器与用户的网络连接</li>
<li>这部分的配置对 Nginx 的性能影响较大，在实际中应该灵活配置</li>
</ul>
<h3 id="http-块"><a href="#http-块" class="headerlink" title="http 块"></a>http 块</h3><ul>
<li>是 Nginx 服务器配置中最频繁的部分，代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里</li>
<li>http 块中也可以包括 http 全局块、 server块</li>
</ul>
<h3 id="http-全局块"><a href="#http-全局块" class="headerlink" title="http 全局块"></a>http 全局块</h3><ul>
<li>http全局块配置的指令包括文件引入、MIME-TYPE 定义、日志自定义、连接超时时间、单链接请求数上限等。</li>
</ul>
<h3 id="sever-块"><a href="#sever-块" class="headerlink" title="sever 块"></a>sever 块</h3><ul>
<li>这块和虚拟主机有密切关系，虚拟主机从用户角度看，和一台独立的硬件主机是完全一样的，该技术的产生是为了节省互联网服务器硬件成本。后面会详细介绍虚拟主机的概念。</li>
<li>每个 http 块可以包括多个 server 块，而每个 server 块就相当于一个虚拟主机。</li>
<li>而每个 server 块也分为全局 server 块，以及可以同时包含多个 locaton 块。</li>
</ul>
<h3 id="location-块"><a href="#location-块" class="headerlink" title="location 块"></a>location 块</h3><ul>
<li>一个 server 块可以配置多个 location 块。</li>
<li>这块的主要作用是基于 Nginx 服务器接收到的请求字符串（例如 server_name/uri-string），对虚拟主机名称（也可以是IP别名）之外的字符串（例如 前面的 /uri-string）进行匹配，对特定的请求进行处理。<strong>地址定向、数据缓存和应答控制</strong>等功能，还有许多第三方模块的配置也在这里进行。</li>
</ul>
<h2 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h2><ul>
<li>web服务器最重要的任务是对外提供文件，例如(图片或者静态HTML网页)。</li>
</ul>
<h3 id="提供静态资源内容"><a href="#提供静态资源内容" class="headerlink" title="提供静态资源内容"></a>提供静态资源内容</h3><ul>
<li>通常，配置文件包含几个server块指令，这些块指令通过不同的服务名字（server names）分发监听（distinguished listen）在不同的端口。</li>
<li>一旦nginx决定哪个服务器处理请求，它就会根据 server 块指令中定义的 location 指令的参数匹配请求头中指定的URI。</li>
<li>在server块指令中添加 location 指令：<figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">location</span> <span class="title">/ &#123;</span></span><br><span class="line"><span class="title"> root</span> /data/www;</span><br><span class="line">&#125;</span><br><span class="line">`</span><br></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>这个location块详述了与URI请求相匹配的“/”前缀。如果匹配到请求，这个 URI 会被转到 root 指令的路径。也就是说，所有请求文件都会直接请求到本地文件系统的/data/www路径。<strong><em>如果有多个匹配的location块，nginx会选择最长前缀的那个</em></strong>。上面提供的location块是长度只有1的最短前缀，因此，其它所有的location块都匹配失败的话，这个location块指令才会被使用。</p>
<ul>
<li>添加第二个location块：<figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">location</span> <span class="title">/images</span> &#123;</span><br><span class="line"> root /data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</blockquote>
<blockquote>
<p>这个会匹配以/images开头的请求（/也会匹配请求，只不过这个前缀更短）。</p>
</blockquote>
<ul>
<li>一个正常的服务器配置文件监听在80端口上，并且可以在本机上成功访问<a href="http://localhost/。" target="_blank" rel="noopener">http://localhost/。</a></li>
<li>以/images/开头请求的URI地址，服务器会从/data/images文件夹下面返回对应的文件。例如，请求/data/images/example.png这个文件，nginx服务器会返回<a href="http://localhost/images/example.png。" target="_blank" rel="noopener">http://localhost/images/example.png。</a></li>
<li><p>如果服务器没有这个文件会返回404 错误。不是以/images/开头的请求,就会被映射到/data/www 文件夹。例如, 请求nginx/data/www/some/example.html,服务器会响应<a href="http://localhost/some/example.html" target="_blank" rel="noopener">http://localhost/some/example.html</a> 这个文件。</p>
</li>
<li><p>为了应用一个新的配置文件，如果nginx还没有启动，就直接启动nginx服务器，如果已经启动，直接使用下面指令发送到nginx的主进程中，如下: 如果nginx尚未启动，则启动nginx，或者向nginx的主进程发送重新加载信号，执行:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; nginx -s reload</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="反向代理"><a href="#反向代理" class="headerlink" title="反向代理"></a>反向代理</h3><ul>
<li>正向代理代理客户端，反向代理代理服务器</li>
<li>反向代理，其实客户端对代理是无感知的，因为客户端不需要任何配置就可以访问，我们只需要将请求发送到反向代理服务器，由反向代理服务器去选择目标服务器获取数据后，在返回给客户端，此时反向代理服务器和目标服务器对外就是一个服务器，暴露的是代理服务器地址，隐藏了真实服务器IP地址。</li>
</ul>
<h4 id="反向代理配置"><a href="#反向代理配置" class="headerlink" title="反向代理配置"></a>反向代理配置</h4><ul>
<li><p>例：使用 Ngwmeinx 反向代理 localhost:8000 直接跳转到 <a href="http://localhost:3000" target="_blank" rel="noopener">http://localhost:3000</a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">      listen       8000;</span><br><span class="line">      #listen       somename:8080;</span><br><span class="line">      server_name  somename  alias  another.alias;</span><br><span class="line"></span><br><span class="line">      location / &#123;</span><br><span class="line">          proxy_pass   http://localhost:3000;</span><br><span class="line">          index  index.html index.htm;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="listen"><a href="#listen" class="headerlink" title="listen"></a>listen</h5><p>配置网络监听，主要语法结构有三种</p>
<ol>
<li><p>配置监听的IP地址</p>
<figure class="highlight accesslog"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">listen address<span class="string">[:port]</span> <span class="string">[default_server]</span> <span class="string">[setfib=number]</span> <span class="string">[backlog=number]</span> <span class="string">[rcvbuf=size]</span> <span class="string">[sndbuf=size]</span> <span class="string">[deferred]</span> <span class="string">[accept_filter=filter]</span> <span class="string">[bind]</span> <span class="string">[ssl]</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>配置监听端口</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">listen port[default_server] [<span class="attribute">setfib</span>=number] [<span class="attribute">backlog</span>=number] [<span class="attribute">rcvbuf</span>=size] [<span class="attribute">sndbuf</span>=size] [<span class="attribute">accept_filter</span>=filter] [deferred] [bind] [<span class="attribute">ipv6only</span>=on|off] [ssl];</span><br></pre></td></tr></table></figure>
</li>
<li><p>配置 UNIX Domain Socket</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">listen</span> <span class="selector-tag">unix</span><span class="selector-pseudo">:path</span> <span class="selector-attr">[default_server]</span>  <span class="selector-attr">[backlog=number]</span> <span class="selector-attr">[rcvbuf=size]</span> <span class="selector-attr">[sndbuf=size]</span> <span class="selector-attr">[accept_filter=filter]</span> <span class="selector-attr">[deferred]</span> <span class="selector-attr">[bind]</span> <span class="selector-attr">[ssl]</span>;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<ul>
<li><p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">listen *:80 | *:8080  #监听所有80端口和8080端口</span><br><span class="line">listen  IP_address:port   #监听指定的地址和端口号</span><br><span class="line">listen  IP_address     #监听指定ip地址所有端口</span><br><span class="line">listen port     #监听该端口的所有IP连接</span><br></pre></td></tr></table></figure>
</li>
<li><p>下面分别解释每个选项的具体含义：</p>
<blockquote>
<p><code>address</code> : IP地址，如果是 IPV6地址，需要使用中括号[] 括起来，比如[fe80::1]等。<br><code>address</code> : IP地址，如果是 IPV6地址，需要使用中括号[] 括起来，比如[fe80::1]等。<br><code>port</code> : 端口号，如果只定义了IP地址，没有定义端口号，那么就使用80端口。<br><code>path</code> : socket文件路径，如 var/run/nginx.sock等。<br><code>default_server</code> : 标识符，将此虚拟主机设置为 address:port 的默认主机。（在 nginx-0.8.21 之前使用的是 default 指令）<br><code>setfib</code> = number : Nginx-0.8.44 中使用这个变量监听 socket 关联路由表，目前只对 FreeBSD 起作用，不常用。<br><code>backlog</code> = number : 设置监听函数listen()最多允许多少网络连接同时处于挂起状态，在 FreeBSD 中默认为 -1,其他平台默认为511.<br><code>rcvbuf</code> = size : 设置监听socket接收缓存区大小。<br><code>sndbuf</code> = size : 设置监听socket发送缓存区大小。<br><code>deferred</code> : 标识符，将accept()设置为Deferred模式。<br><code>accept_filter = filter</code> : 设置监听端口对所有请求进行过滤，被过滤的内容不能被接收和处理，本指令只在 FreeBSD 和 NetBSD 5.0+ 平台下有效。filter 可以设置为 dataready 或 httpready 。<br><code>bind</code> : 标识符，使用独立的bind() 处理此address:port，一般情况下，对于端口相同而IP地址不同的多个连接，Nginx 服务器将只使用一个监听指令，并使用 bind() 处理端口相同的所有连接。<br><code>ssl</code> : 标识符，设置会话连接使用 SSL模式进行，此标识符和Nginx服务器提供的 HTTPS 服务有关。</p>
</blockquote>
</li>
</ul>
<h5 id="server-name"><a href="#server-name" class="headerlink" title="server_name"></a>server_name</h5><ul>
<li><p>用于虚拟主机的配置，通常两种配置方法：</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">server_name</span></span> name...;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>对于 name 来说，可以只有一个名称，也可以有多个名称，中间用空格隔开。而每个名字由两段或者三段组成，每段之间用 <code>.</code> 隔开</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">server_name baidu.com www.baidu.com</span><br></pre></td></tr></table></figure>
</li>
<li><p>可以使用通配符 <code>*</code>，但通配符只能用在由 <strong><em>三段字符</em></strong> 诸城的首段或者尾端</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">server_name baidu.com www.baidu.com</span><br></pre></td></tr></table></figure>
</li>
<li><p>可以使用正则表达式，用“~”作为正则表达式字符串的开始标记</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">server_name ~^www\d+\.123\.com$;</span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ul>
<ul>
<li><p>匹配优先级</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">1. 准确匹配 server_name</span><br><span class="line">2. 通配符在开始时匹配 server_name 成功</span><br><span class="line">3. 通配符在结尾时匹配 server_name 成功</span><br><span class="line">4. 正则表达式匹配 server_name 成功</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li>基于 IP 地址的虚拟主机配置<br>语法结构和基于域名匹配一样，而且不需要考虑通配符和正则表达式的问题。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">server_name 192.168.1.1</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="location"><a href="#location" class="headerlink" title="location"></a>location</h5><p>用于匹配 URL<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"> location [ = | ~ | ~* | ^~] uri &#123; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li><code>=</code> ：用于不含正则表达式的 uri 前，要求请求字符串与 uri 严格匹配，如果匹配成功，就停止继续向下搜索并立即处理该请求。</li>
<li><code>~</code> ：用于表示 uri 包含正则表达式，并且区分大小写。</li>
<li><code>~*</code> ：用于表示 uri 包含正则表达式，并且不区分大小写。</li>
<li><code>^~</code> ：用于不含正则表达式的 uri 前，要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后，立即使用此 location 处理请求，而不再使用 location 块中的正则 uri 和请求字符串做匹配。<blockquote>
<p>注意：如果 uri 包含正则表达式，则必须要有 ~ 或者 ~* 标识</p>
</blockquote>
</li>
</ol>
<h5 id="proxy-pass"><a href="#proxy-pass" class="headerlink" title="proxy_pass"></a>proxy_pass</h5><p>设置代理服务器的地址,可以是 主机名称、IP 地址加端口，URI 等<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">prox_pass URL</span><br></pre></td></tr></table></figure></p>
<h2 id="配置图解"><a href="#配置图解" class="headerlink" title="配置图解"></a>配置图解</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#user nobody; # user 指定运行 nginx 的用户和组（第一个参数为用户第二个为组，这里只有用户）</span><br><span class="line">worker_processes  1; #运行时使用CPU的个数</span><br><span class="line"></span><br><span class="line">#error_log  logs/error.log; # 指定错误日志为 logs/ 目录下的 error.log 文件</span><br><span class="line">#error_log  logs/error.log  notice; # 指定错误日志，并指定写入格式为 notice</span><br><span class="line">#error_log  logs/error.log  info; # 指定错误日志，并指定写入格式为 info</span><br><span class="line"></span><br><span class="line">#pid        logs/nginx.pid; # 指定 pid 文件（存放主进程 pid 号）</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">events &#123;</span><br><span class="line">    worker_connections  1024; #一个woeker进程的最大连接数</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#Nginx用作虚拟主机时使用。每一个server模块生成一个虚拟主机。</span><br><span class="line">http &#123;</span><br><span class="line">    include       mime.types; #定义MIME类型和后缀名关联的文件的位置</span><br><span class="line">    default_type  application/octet-stream; #指定mime.types文件中没有记述到的后缀名的处理方法</span><br><span class="line"></span><br><span class="line">    # 写入格式 main 的内容格式如下</span><br><span class="line">    #log_format  main  &apos;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &apos;</span><br><span class="line">    #                  &apos;$status $body_bytes_sent &quot;$http_referer&quot; &apos;</span><br><span class="line">    #                  &apos;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&apos;;</span><br><span class="line"></span><br><span class="line">    #access_log  logs/access.log  main; # 指定访问日志和写入格式为 main</span><br><span class="line"></span><br><span class="line">    sendfile        on;  #是 否使用OS的sendfile函数来传输文件</span><br><span class="line">    #tcp_nopush     on; # 启用或者禁用使用套接字选项（仅在 sendfile 使用时使用）</span><br><span class="line"></span><br><span class="line">    #keepalive_timeout  0;  # 0 值禁用保持活动的客户端连接</span><br><span class="line">    keepalive_timeout  65;  #HTTP连接的持续时间。设的太长会使无用的线程变的太多</span><br><span class="line"></span><br><span class="line">    #gzip  on; # 启用或者禁用 gzip</span><br><span class="line"></span><br><span class="line">    # 虚拟主机配置模块</span><br><span class="line">    server &#123;</span><br><span class="line">        listen       8888; #监听端口</span><br><span class="line"></span><br><span class="line">        server_name  localhost; #服务地址</span><br><span class="line"></span><br><span class="line">        charset utf-8;   #编码方式</span><br><span class="line">        #charset koi8-r;</span><br><span class="line"></span><br><span class="line">        #root /var/www; #你的网站根目录</span><br><span class="line">        root  /Users/b/Desktop;</span><br><span class="line"></span><br><span class="line">        error_log  logs/error.log;</span><br><span class="line">        #access_log  logs/host.access.log  main;</span><br><span class="line">        location  /a/ &#123;</span><br><span class="line">            alias /Users/b/Desktop/Nginx_files/; # 别名</span><br><span class="line">            index  6.gif IMG_2021.jpg;  # 定义索引，按顺序匹配</span><br><span class="line">        &#125;</span><br><span class="line">        #若按照上述配置的话，则访问/a/目录里面的文件时，ningx会自动去/Users/b/Desktop/Nginx_files/目录找文件</span><br><span class="line"></span><br><span class="line">        # 将特定的文件或目录重新定位，如 php 文件，image 目录等</span><br><span class="line">        location /Nginx_files/ &#123;</span><br><span class="line">            root  /Users/b/Desktop;</span><br><span class="line">            index  6.gif IMG_2021.jpg;  # 定义索引，按顺序匹配</span><br><span class="line">        &#125;</span><br><span class="line">        #若按照这种配置的话，则访问/Nginx_files/目录下的文件时，nginx会去/Users/b/Desktop/Nginx_files/目录下找文件。</span><br><span class="line">        error_page  404              /404.html;  # 定义显示 404 错误的 uri</span><br><span class="line"></span><br><span class="line">        # redirect server error pages to the static page /50x.html</span><br><span class="line">        #</span><br><span class="line"></span><br><span class="line">        error_page   500 502 503 504  /50x.html;</span><br><span class="line"></span><br><span class="line">        location = /50x.html &#123;   # location 精准匹配 &apos;/50x.html&apos;</span><br><span class="line">            root   html;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        # proxy the PHP scripts to Apache listening on 127.0.0.1:80</span><br><span class="line">        #</span><br><span class="line">        #location ~ \.php$ &#123;  # 正则表达式: .php文件走的路径</span><br><span class="line">        #    proxy_pass   http://127.0.0.1;</span><br><span class="line">        #&#125;</span><br><span class="line"></span><br><span class="line">        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000</span><br><span class="line">        #</span><br><span class="line">        #location ~ \.php$ &#123;</span><br><span class="line">        #    root           html;</span><br><span class="line">        #    fastcgi_pass   127.0.0.1:9000;  #走fastcgi 路径</span><br><span class="line">        #    fastcgi_index  index.php;</span><br><span class="line">        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name; #定义的根目录 以及 请求的脚名</span><br><span class="line">        #    include        fastcgi_params; # 请求参数</span><br><span class="line">        #&#125;</span><br><span class="line"></span><br><span class="line">        # deny access to .htaccess files, if Apache&apos;s document root</span><br><span class="line">        # concurs with nginx&apos;s one</span><br><span class="line">        #</span><br><span class="line">        #location ~ /\.ht &#123;</span><br><span class="line">        #    deny  all;</span><br><span class="line">        #&#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # another virtual host using mix of IP-, name-, and port-based configuration</span><br><span class="line">    #</span><br><span class="line">    #server &#123;</span><br><span class="line">    #    listen       8000;</span><br><span class="line">    #    listen       somename:8080;</span><br><span class="line">    #    server_name  somename  alias  another.alias;</span><br><span class="line"></span><br><span class="line">    #    location / &#123;</span><br><span class="line">    #        root   html;</span><br><span class="line">    #        index  index.html index.htm;</span><br><span class="line">    #    &#125;</span><br><span class="line">    #&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # HTTPS server</span><br><span class="line">    #</span><br><span class="line">    #server &#123;</span><br><span class="line">    #    listen       443 ssl;</span><br><span class="line">    #    server_name  localhost;</span><br><span class="line"></span><br><span class="line">    #    ssl_certificate      cert.pem;</span><br><span class="line">    #    ssl_certificate_key  cert.key;</span><br><span class="line"></span><br><span class="line">    #    ssl_session_cache    shared:SSL:1m;</span><br><span class="line">    #    ssl_session_timeout  5m;</span><br><span class="line"></span><br><span class="line">    #    ssl_ciphers  HIGH:!aNULL:!MD5;</span><br><span class="line">    #    ssl_prefer_server_ciphers  on;</span><br><span class="line"></span><br><span class="line">    #    location / &#123;</span><br><span class="line">    #        root   html;</span><br><span class="line">    #        index  index.html index.htm;</span><br><span class="line">    #    &#125;</span><br><span class="line">    #&#125;</span><br><span class="line">    include servers/*;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h2><ul>
<li>苗泽老师的《Nginx高性能Web服务器详解》</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Nginx/" rel="tag"># Nginx</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/09/06/前端设计模式（状态模式）/" rel="next" title="前端设计模式（状态模式）">
                <i class="fa fa-chevron-left"></i> 前端设计模式（状态模式）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/01/26/mongodb/" rel="prev" title="mongodb">
                mongodb <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/IMG_2021.jpg" alt="两万">
            
              <p class="site-author-name" itemprop="name">两万</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/bevexed" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://cn.vuejs.org/" title="Vue" target="_blank">Vue</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bevexed.top/frontEnd/H5_Daily/canvas/demo/FlappyBird" title="FlapBird" target="_blank">FlapBird</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简述-Nginx"><span class="nav-text">简述 Nginx</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#启动-停止-和重新加载配置文件"><span class="nav-text">启动, 停止, 和重新加载配置文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置文件结构"><span class="nav-text">配置文件结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#全局块"><span class="nav-text">全局块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#event-块"><span class="nav-text">event 块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#http-块"><span class="nav-text">http 块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#http-全局块"><span class="nav-text">http 全局块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sever-块"><span class="nav-text">sever 块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#location-块"><span class="nav-text">location 块</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#功能"><span class="nav-text">功能</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#提供静态资源内容"><span class="nav-text">提供静态资源内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反向代理"><span class="nav-text">反向代理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#反向代理配置"><span class="nav-text">反向代理配置</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#listen"><span class="nav-text">listen</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#server-name"><span class="nav-text">server_name</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#location"><span class="nav-text">location</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#proxy-pass"><span class="nav-text">proxy_pass</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置图解"><span class="nav-text">配置图解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文档"><span class="nav-text">参考文档</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">两万</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">26.6k</span>
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.bevexed.top/2019/09/06/nginx入门指南/';
          this.page.identifier = '2019/09/06/nginx入门指南/';
          this.page.title = 'Nginx入门指南';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: true,
        appId: 'EoJiOrKeNWgSwq0eXmK0VK7V-gzGzoHsz',
        appKey: 'H1riqYCRgB88YzWIOinxfaAg',
        placeholder: '说点啥吧......',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EoJiOrKeNWgSwq0eXmK0VK7V-gzGzoHsz", "H1riqYCRgB88YzWIOinxfaAg");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
